﻿//#define TESTING
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using NativeWifi;
using WNADEP.DataCenter;
using WNADEP.DataCenter.NetworkDataSet;
using System.IO;
using System.Data;
using Microsoft.Research.DynamicDataDisplay.DataSources;
using Microsoft.Research.DynamicDataDisplay.Charts;
using Microsoft.Research.DynamicDataDisplay;
using WNADEP.DataCenter.DisplayDataSet;
using System.Collections.ObjectModel;
using System.Windows.Controls.DataVisualization.Charting;
using System.Diagnostics;
using WNADEP.TCPService;
using System.Threading;

namespace WNADEP
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {

        #region Fields

        private enum sourceMenuItemId
        {
            localSourcesMenuItemId,
            remoteSourcesMenuItemId,
            kddSourcesMenuItemId
        }

        private bool isScanning;
        private List<WIFISSID> _ssids;
        private WlanClient.WlanInterface _intf;
        private WlanClient _wlanClient;

        private Image imageStart = null;
        private Image imageStop = null;

        private EnumerableDataSource<DateTime> varDateTime = null;
        private List<DateTime> dateTimeList = new List<DateTime>();

        private List<WIFIRSSIDisplay> rssiDisplay = new List<WIFIRSSIDisplay>();
        private WIFIRSSIDisplay currentRssiDisplay = null;

        private ServiceManager _serviceManager = null;

        private Thread _threadLocal;
        private Thread _threadRemote;
        private Thread _threadSimulation;
        private DataCenter.DataCenter _dataCenter;
        CompositeDataSource compositeDataSource;
        public ObservableCollection<KeyValuePair<string, int>> _valueList { get; set; }

        System.Windows.Threading.DispatcherTimer dtimer;
        System.Timers.Timer timer;

        #endregion Fields

        public MainWindow()
        {
            InitializeComponent();
            CustomInit();
        }

        private void CustomInit()
        {
            // read config.ini
            //selectedSourceMenuItem = localSourcesMenuItem; //from config.ini get lastSelectedMenuItem
            //加载图像
            imageStart = new Image();
            imageStop = new Image();
            imageStart.Source = new BitmapImage(new Uri(  System.Environment.CurrentDirectory+ "\\startBtn.jpg"));
            imageStop.Source = new BitmapImage(new Uri(System.Environment.CurrentDirectory+"\\stopBtn.png"));
            
            //
            _serviceManager = new ServiceManager();
            _serviceManager.InitService("0.0.0.0", 4567);
            //获取无线网卡句柄
            isScanning = false;
            // Wlan Interface or get it from config.ini
            _wlanClient = new WlanClient();
            _intf = null;
            foreach (WlanClient.WlanInterface intf in _wlanClient.Interfaces)
            {
                if (intf.CurrentConnection.isState == Wlan.WlanInterfaceState.Connected)
                {
                    _intf = intf;
                }
            }
            //_intf = Wlan.
            //localScanView.DataContext = ocSSIDs;


            //Add Fake Data
            AddFakeData();
            //DisplayData
            Display_Loaded();
            //绑定数据上下文
            this.localLineChart.DataContext = this._valueList;
            //创建线程对象
            _dataCenter = new DataCenter.DataCenter(_intf);
            _threadLocal = new Thread( _dataCenter.UpdateGlobalSsids );

            _threadRemote = new Thread(_serviceManager.StartService);
        }

        [Conditional("TESTING")]
        private void AddFakeData()
        {

            //添加KDD模拟数据
            List<KDDCupFeature> data_set = new List<KDDCupFeature>();
            List<string> temp_dataset = new List<string>();
            using (FileStream fs = File.Open(@"kddSample.txt", FileMode.Open))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    while (true)
                    {
                        string tmp = sr.ReadLine();
                        if (tmp == null)
                            break;
                        temp_dataset.Add(tmp);
                    }
                }
            }
            //string[] temp_dataset = { "2, tcp, smtp, SF, 1684, 363, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0.00, 0.00, 0.00, 0.00, 1.00, 0.00, 0.00, 104, 66, 0.63, 0.03, 0.01, 0.00, 0.00, 0.00, 0.00, 0.00, normal" };
            foreach (string features_str in temp_dataset)
            {
                KDDCupFeature data = new KDDCupFeature();
                data.ReadBaseFeatureByString(features_str);
                data_set.Add(data);
            }
            //kddScanView.LoadingRow += new EventHandler<DataGridRowEventArgs>(DG_LoadingRow);

            kddScanView.ItemsSource = data_set;


            //添加本地数据
            //localScanView.LoadingRow += new EventHandler<DataGridRowEventArgs>(DG_LoadingRow);
            //localScanView.ItemsSource = 


            //添加远程数据
            //remoteScanView.LoadingRow += new EventHandler<DataGridRowEventArgs>(DG_LoadingRow);
            List<RemoteData> temp_remote = new List<RemoteData>();
            temp_remote = DataCenter.DataCenter.GenerateFakeRemoteData();
            remoteScanView.ItemsSource = temp_remote;
        }
        [Conditional("TESTING")]
        private void Display_Loaded()
        {
            Random rnd = new Random();

            varDateTime = new EnumerableDataSource<DateTime>(dateTimeList);

            dateTimeList.Add(DateTime.Now);
            
            currentRssiDisplay.rssiData.Add(rnd.Next(256));

            varDateTime.SetXMapping(x => x.TimeOfDay.TotalSeconds);

            compositeDataSource = new CompositeDataSource(varDateTime, currentRssiDisplay.varRSSI);

            //localPlotter.AddLineGraph(compositeDataSource, Colors.Red, 1, currentRssiDisplay.ssid);

            for (int i = 0; i < 100; i++)
            {
                dateTimeList.Add(DateTime.Now);
                currentRssiDisplay.rssiData.Add(rnd.Next(256));
            }
            varDateTime.RaiseDataChanged();
            currentRssiDisplay.varRSSI.RaiseDataChanged();


            ObservableCollection<item> items1 = new ObservableCollection<item>()
          {
            new item(){key="tcp",value=0.4},
            new item(){key="udp",value=0.1},
            new item(){key="icmp",value=0.5},

          };

            (chart1.Series[0] as ColumnSeries).ItemsSource = items1;
            (chart1.Series[0] as ColumnSeries).Title = "比例";
            
        }

        void DG_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            int index = e.Row.GetIndex();
            if (index % 2 == 0)
            {
                e.Row.Background = Brushes.Gray;  // color
                
            }
            //switch (dgv["isEmergent"].ToString())
            //{
            //    case "True":
            //        e.Row.Background = new SolidColorBrush(Colors.Red);
            //        break;
            //    default:
            //        break;
            //}
            //e.Row.Header = index + 1;
        }


        private void scanBtn_Click(object sender, RoutedEventArgs e)
        {

            if (isScanning)
            {
                isScanning = false;
                //scanBtn.IsEnabled = true;
                scanBtn.Content = imageStart;
                _dataCenter.RequestStop();
                _serviceManager.RequestStop();
                //scanBtn.Content = "停止";
                if(timer != null)
                {
                    timer.Stop();
                }
                //_serviceManager.StopService();
            }
            else
            {
                isScanning = true;
                //scanBtn.IsEnabled = false;
                scanBtn.Content = imageStop;
                
                _threadLocal.Start();
                _serviceManager.RequestStart();
                _threadRemote.Start();
                //_serviceManager.InitService("192.168.1.104", 4567);
                //_serviceManager.StartService();
                //scanBtn.Content = "开始";
                if (timer == null)
                {
                    timer = new System.Timers.Timer();
                }
                timer.Interval = 3000;

                timer.Elapsed += timer_Elapsed;

                timer.Start();
            }
        }

        void timer_Elapsed(object sender, EventArgs e)
        {
            this.Dispatcher.BeginInvoke( new Action(() => {
                this._ssids = new List<WIFISSID>();
                this._ssids.AddRange(_dataCenter.globalSsids);
                this.localScanView.ItemsSource = null;
                this.localScanView.ItemsSource = _ssids;


                List<RemoteData> remoteList = new List<RemoteData>();
                if (_serviceManager.globalRemoteData != null)
                    remoteList.AddRange(_serviceManager.globalRemoteData);
                this.remoteScanView.ItemsSource = remoteList;


            }), null);

        }

        private void TitleView_Loaded(object sender, RoutedEventArgs e)
        {
        }

        private void testBtn_Click(object sender, RoutedEventArgs e)
        {
            _ssids = DataCenter.DataCenter.ScanSSID(_intf);

            localScanView.ItemsSource = _ssids;
        }

        private void kddScanView_Loaded(object sender, RoutedEventArgs e)
        {
            //for (int i = 0; i < kddScanView.Items.Count; i++)
            //{
            //    var drv = kddScanView.Items[i] as DataRowView;
            //    if( drv == null)
            //        MessageBox.Show("!!!");
            //    //switch (dgv.DataView.ToString())
            //    //{
            //    //    case "True":
            //    //        var row = kddScanView.ItemContainerGenerator.ContainerFromIndex(i) as DataGridRow;
            //    //        row.Background = new SolidColorBrush(Colors.Red);
            //    //        break;
            //    //    default:
            //    //        break;
            //    //}
            //    //if (dgv["告警"].ToString().Equals(compare))
            //    //{
            //    //    var row = kddScanView.ItemContainerGenerator.ContainerFromIndex(i) as DataGridRow;
            //    //    row.Background = new SolidColorBrush(Colors.Red);
            //    //}
            //}
        }


    }
    public class item
    {
        public double value { get; set; }
        public string key { get; set; }
    }
}
